/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.aksw.treelearning.data;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;

/**
 *
 * @author ngonga
 */
public class CsvReader {

    public static String SEP = "\t";

    /**
     * Read a CSV file and write the content in a cache. The first line is the
     * name of the properties.
     *
     * @param c Cache in which the content is to be written
     */
    public static Cache readFile(String file) {
        Cache c = new MemoryCache();
        Logger logger = Logger.getLogger("LIMES");
        String s = "";
        try {
            // in case a CSV is use, endpoint is the file to read
            BufferedReader reader = new BufferedReader(new FileReader(file));
            s = reader.readLine();
            String split[];
            //first read name of properties. URI = first column
            if (s != null) {
                ArrayList<String> properties = new ArrayList<String>();
                //split first line
                split = s.split(SEP);
                properties.addAll(Arrays.asList(split));
                logger.info("Properties = " + properties);
                s = reader.readLine();
                String rawValue;
                String id, value;
                while (s != null) {
                    split = s.split(SEP);
                    //split = DataCleaner.separate(s, SEP, properties.size());
                    id = split[0];
                    //logger.info(id);
                    for (String propertyLabel : properties) {
                        if (split.length > properties.indexOf(propertyLabel)) {
                            rawValue = split[properties.indexOf(propertyLabel)];
                            c.addTriple(id, propertyLabel, rawValue.replaceAll(Pattern.quote("@en"), ""));
                        }
                    }
                    s = reader.readLine();
                }
            } else {
                logger.warn("Input file " + file + " was empty or faulty");
            }
            reader.close();
            logger.info("Retrieved " + c.size() + " statements");
        } catch (Exception e) {
            logger.fatal("Exception:" + e.getMessage());
            logger.warn(s);
            e.printStackTrace();
        }
        return c;
    }
}
